/**
 * 扫雷游戏
 * 初级 10个雷 9*9 
 * 中级 40个雷 16*16
 * 高级 99个雷 16*30
 * 
 * 生成一个这样的二维数组
 * [
 *  [0, 0, 0, 0, 0, 0, 0, 1, 9],
 *  [2, 2, 1, 0, 0, 0, 1, 2, 9],
 *  [0, 0, 1, 9, 9, 2, 9, 9, 1]
 * ]
 * 数字9代表的是雷，1，2,3,4代表雷的数量，0代表没有雷
 * 
 */


function Mine(row, col, num) {
  this.row = row;
  this.col = col;
  this.num = num;
  this.dom = document.querySelector('.game-box');
  this.minNum = document.querySelector('.mineNum');
  // 存放等级的参数;
  this.remainNum = this.num;
  this.params = [];
  // 放二维数组的地图
  this.map = [];
}


// 生成一张二维地图
Mine.prototype.setMap = function () {
  // 生成行
  var self = this;
  var r = function () {
    for (var i = 0; i < self.row; i++) {
      self.map[i] = new Array();
    };
  }
  // 列
  var c = function () {
    for (var i = 0; i < self.map.length; i++) {
      for (var j = 0; j < self.col; j++) {
        self.map[i][j] = 0;
      }
    };
  }
  r();
  c();
};

// 生成随机的地雷并放入map中
Mine.prototype.randomMine = function () {
  var self = this;
  var randomM = function () {
    var x = Math.floor(Math.random() * self.row);
    var y = Math.floor(Math.random() * self.col);
    // 随机生成一组坐标，重复就重新生成
    if (self.map[x][y] != 9) {
      self.map[x][y] = 9;
    } else {
      randomM();
    }
  }
  for (var i = 0; i < this.num; i++) {
    randomM();
  }
}

// 给所有雷的周围加1
Mine.prototype.addNum = function () {
  var self = this;
  var plus = function (i, j) {
    if (i >= 0 && j >= 0 && i < self.row && j < self.col) {
      if (self.map[i][j] !== 9) {
        self.map[i][j] += 1;
      };
    }
  };
  for (var i = 0; i < this.row; i++) {
    for (var j = 0; j < this.col; j++) {
      if (this.map[i][j] === 9) {
        // 上下6个数字
        for (var k = -1; k < 2; k++) {
          plus(i - 1, j + k);
          plus(i + 1, j + k);
        };
        // 中间两个
        plus(i, j + 1);
        plus(i, j - 1);
      }
    }
  }
}

// 将雷放到页面dom
Mine.prototype.write = function () {
  this.dom.innerHTML = '';
  for (var i = 0; i < this.row; i++) {
    this.dom.innerHTML += `<ul class='row x-${i}' data-x='${i}'></ul>`
  };
  var x = document.querySelectorAll('.row');
  for (var i = 0; i < this.row; i++) {
    for (var j = 0; j < this.col; j++) {
      var m = this.map[i][j];
      x[i].innerHTML += `<li class='col y-${j} num${m}' num='${m}' data-x="${i}" data-y='${j}'></li>`
    }
  };
  // 顺便把雷数量也写到页面
  this.minNum.innerHTML = this.num;

  // console.log(this.map);
};

// 点击显示白色
Mine.prototype.diffusion = function (i, j) {
  if (i < this.row && i >= 0 && j < this.col && j >= 0) {
    var mine = document.querySelector(`.x-${i}`).children[j];
    var num = mine.getAttribute('num');

    // 如果有标记的旗帜，去掉旗帜
    var flag = mine.classList.contains('flag');
    if (flag) {
      mine.classList.toggle('flag');
      this.remainNum++;
      this.minNum.innerHTML = this.remainNum;
    };

    // console.log('扩散颜色', mine.style.backgroundColor);
    if (mine.style.backgroundColor != 'white') {
      if (num <= 9) {
        mine.style.backgroundColor = 'white';
        mine.classList.add('hide');
        // 只有数字是0的时候扩散
        if (num === '0') {
          this.showMine(i, j);
        } else {
          // 数字不是0则写出数字在页面上
          mine.innerHTML = num;
        }
      }
      // console.log('num', num);
      this.isWin();
    };
  }
};


// 扩散
Mine.prototype.showMine = function (i, j) {
  this.diffusion(i - 1, j - 1);
  this.diffusion(i - 1, j);
  this.diffusion(i - 1, j + 1);
  this.diffusion(i, j - 1);
  this.diffusion(i, j + 1);
  this.diffusion(i + 1, j - 1);
  this.diffusion(i + 1, j);
  this.diffusion(i + 1, j + 1);
};

// 扫雷过程
Mine.prototype.clearMine = function (el) {
  var num = el.getAttribute('num');
  if (num != 0) {
    el.innerText = num;
  }
};


// 绑定点击事件
Mine.prototype.bindClick = function () {
  var self = this;
  var oli = document.querySelectorAll('.row');
  for (var i = 0; i < oli.length; i++) {
    // 左击
    oli[i].addEventListener('click', function (e) {
      var el = e.target;
      var flag = el.classList.contains('hide');
      var mine = el.getAttribute('num');
      if (el.tagName == 'LI' && !flag) {
        if (mine !== '9' && el.style.backgroundColor !== 'white') {
          console.log('点开一个了', 'a' + mine);
          el.style.backgroundColor = 'white';
          el.classList.add('hide');
          self.clearMine(el);
          self.isWin();
          // 点击空白的地方，扩散开始
          if (mine === '0') {
            var x = parseInt(el.dataset.x);
            var y = parseInt(el.dataset.y);
            // console.log('给我力量', typeof x, typeof y, x, y);
            self.showMine(x, y);
          }
        } else if (mine === '9') {
          alert('你输了');
          // 失败了显示所有地雷
          var col = document.querySelectorAll('.col');
          for (var i = 0; i < col.length; i++) {
            var num = col[i].getAttribute('num');
            if (num === '9') {
              col[i].classList.add('boom');
            }
          }
        };

      }
    })
    // 右击
    oli[i].addEventListener('contextmenu', function (e) {
      e.preventDefault();
      var el = e.target;
      var num = el.getAttribute('num');
      var flag = el.classList.contains('flag');
      let hide = el.classList.contains('hide');
      if (el.tagName == 'LI') {
        // 被左击打开的不能右击标记
        if (!flag && !hide) {
          self.remainNum--;
          if (self.num <= 0) {
            self.num = 0;
            alert('不能标记地雷了');
            return;
          };
          el.classList.add('flag');
          if (num === '9') {
            el.classList.add('flagTrue');
          }
        } else {
          el.classList.remove('flag');
          el.classList.remove('flagTrue');
          self.remainNum++;
          if (self.remainNum >= self.num) {
            self.remainNum = self.num;
          }
        };
        // console.log('剩余地雷',self.remainNum, self.num);
        self.minNum.innerHTML = self.remainNum;
        self.isWin();
        console.log(el);
      }
    })
  };

  // 等级按钮绑定点击事件
  var oBtn = document.querySelector('.level');
  oBtn.addEventListener('click', function (e) {
    var el = e.target;
    var classname = el.classList[0];
    switch (classname) {
      case 'primary':
        self.row = 9;
        self.col = 9;
        self.num = 10;
        self.init();
        break;
      case 'intermediate':
        self.row = 16;
        self.col = 16;
        self.num = 40;
        self.init();
        break;
      case 'advanced':
        self.row = 16;
        self.col = 30;
        self.num = 99;
        self.init();
        break;
      case 'restart':
        self.init();
        break;
      default:
        break;
    }
    // console.log(el, classname);
  });

};



// 判断是否赢了
Mine.prototype.isWin = function () {
  var hd = document.querySelectorAll('.hide').length;
  let flagTrue = document.querySelectorAll('.flagTrue').length;
  var allNum = this.row * this.col;
  // 2种情况，赢游戏
  // 1. 右击旗帜都是地雷
  // 2. 剩余没点开的数量=地雷总数量
  if (flagTrue == this.num || allNum - hd == this.num) {
    alert('大吉大利, 今晚吃鸡');
  }
  console.log('没赢呢，别激动');
};

// 初始化
Mine.prototype.init = function () {
  console.clear();
  this.remainNum = this.num;
  this.setMap();
  this.randomMine();
  this.addNum();
  this.write();
  this.bindClick();
};

Mine.prototype.init.prototype = Mine.prototype;

// 
var mine = new Mine(9, 9, 10);
mine.init();